package com.dycloud.project.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.dycloud.project.constant.Constants;
import com.dycloud.project.domain.Course;
import com.dycloud.project.domain.SysUser;
import com.dycloud.project.enums.ReviewStatusEnum;
import com.dycloud.project.exception.ServiceException;
import com.dycloud.project.mapper.CourseMapper;
import com.dycloud.project.request.ReviewCourseRequest;
import com.dycloud.project.security.LoginUser;
import com.dycloud.project.service.ICourseService;
import com.dycloud.project.service.ISysUserService;
import com.dycloud.project.utils.DateUtils;
import com.dycloud.project.utils.SecurityUtils;
import com.dycloud.project.vo.CoursePageVO;
import com.dycloud.project.vo.PushTrendItemVo;
import com.dycloud.project.vo.UserCourseVO;
import com.dycloud.project.web.page.TableDataInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author : renhang
 * @description CourseServiceImpl
 * @date : 2025-07-02 21:51
 **/
@Service("iCourseService")
public class CourseServiceImpl implements ICourseService {
    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询课程信息
     *
     * @param id 课程信息主键
     * @return 课程信息
     */
    @Override
    public UserCourseVO selectCourseById(Long id) {
        Course course = courseMapper.selectCourseById(id);
        UserCourseVO userCourseVO = BeanUtil.copyProperties(course, UserCourseVO.class);
        userCourseVO.setNickName(sysUserService.selectUserById(userCourseVO.getPublishId()).getNickName());
        userCourseVO.setAuditorName(sysUserService.selectUserById(userCourseVO.getAuditorId()).getNickName());
        return userCourseVO;
    }

    /**
     * 查询课程信息列表
     *
     * @param course 课程信息
     * @return 课程信息
     */
    @Override
    public TableDataInfo selectCourseList(Course course) {
        // 租户隔离,admin可以看所有的
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (SecurityUtils.isCommonUser()) {
            course.setPublishId(loginUser.getUserId());
        }
        List<Course> courses = courseMapper.selectCourseList(course);
        if (CollUtil.isEmpty(courses)) {
            return TableDataInfo.build(courses, courses);
        }
        Set<Long> list = courses.stream().map(Course::getPublishId).collect(Collectors.toSet());
        list.addAll(courses.stream().map(Course::getAuditorId).collect(Collectors.toSet()));
        Map<Long, SysUser> sysUserMap = sysUserService.getUserInfoMap(new HashSet<>(list));

        List<CoursePageVO> pageVOList = courses.stream().map(cs -> {
            CoursePageVO pageVO = BeanUtil.copyProperties(cs, CoursePageVO.class);
            pageVO.setNickName(Objects.nonNull(cs.getPublishId()) ? sysUserMap.get(cs.getPublishId()).getNickName() : null);
            if (Objects.nonNull(cs.getAuditorId())) {
                pageVO.setAuditorName(Objects.nonNull(cs.getPublishId()) ? sysUserMap.get(cs.getPublishId()).getNickName() : null);
            }
            return pageVO;
        }).toList();
        return TableDataInfo.build(pageVOList, courses);
    }

    /**
     * 新增课程信息
     *
     * @param course 课程信息
     * @return 结果
     */
    @Override
    public int insertCourse(Course course) {
        // 管理员创建的不需要审核
        if (SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            course.setStatus(ReviewStatusEnum.PUBLISHED.getCode());
            course.setAuditorId(SecurityUtils.getUserId());
            course.setAuditTime(DateUtils.getNowDate());
        }
        course.setCreateTime(DateUtils.getNowDate());
        course.setUpdateTime(DateUtils.getNowDate());
        course.setPublishId(SecurityUtils.getUserId());
        return courseMapper.insertCourse(course);
    }

    /**
     * 修改课程信息
     *
     * @param course 课程信息
     * @return 结果
     */
    @Override
    public int updateCourse(Course course) {
        checkIsReview(course.getId());
        course.setUpdateTime(DateUtils.getNowDate());
        return courseMapper.updateCourse(course);
    }

    /**
     * 批量删除课程信息
     *
     * @param ids 需要删除的课程信息主键
     * @return 结果
     */
    @Override
    public int deleteCourseByIds(Long[] ids) {
        for (Long id : ids) {
            checkIsReview(id);
        }
        return courseMapper.deleteCourseByIds(ids);
    }

    /**
     * 删除课程信息信息
     *
     * @param id 课程信息主键
     * @return 结果
     */
    @Override
    public int deleteCourseById(Long id) {
        return courseMapper.deleteCourseById(id);
    }

    @Override
    public void review(ReviewCourseRequest request) {
        request.getIds().forEach(id -> {
            Course course = courseMapper.selectCourseById(id);
            if (Objects.isNull(course)) {
                throw new RuntimeException("id:" + id + "的课程不存在");
            }
        });

        List<Course> list = request.getIds().stream().map(e -> {
            Course course = new Course();
            course.setId(e);
            course.setAuditorId(SecurityUtils.getUserId());
            course.setStatus(request.getStatus());
            course.setAuditRemark(request.getAuditRemark());
            course.setUpdateTime(DateUtils.getNowDate());
            course.setAuditTime(DateUtils.getNowDate());
            return course;
        }).toList();

        courseMapper.updateCourseList(list);
    }

    @Override
    public void updateIsActive(Long id, Integer isActive) {

        Course course = courseMapper.selectCourseById(id);
        if (Objects.isNull(course)) {
            throw new RuntimeException("id:" + id + "的课程不存在");
        }

        courseMapper.updateCourseActive(CollUtil.newArrayList(id), isActive);
    }

    private void checkIsReview(Long id) {
        Course course = courseMapper.selectCourseById(id);
        if (Objects.isNull(course)) {
            throw new ServiceException("课程不存在");
        }
        if (Objects.equals(course.getIsDel(), Constants.ONE)) {
            throw new ServiceException("课程已删除");
        }
        if (Objects.equals(course.getStatus(), Constants.ONE)) {
            throw new ServiceException("已经发布的课程不能修改");
        }
        if (Objects.equals(course.getIsActive(), Constants.ONE)) {
            throw new ServiceException("开设的课程不能修改");
        }
    }


    @Override
    public int selectCount(Long userId) {
        return courseMapper.selectCount(userId);
    }

    @Override
    public List<PushTrendItemVo> selectPushTrend(Long userId) {
        return courseMapper.selectPushTrend(userId);
    }
}
